<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Json Web Token,token,JJWT,SpringSecurity,认证机制,无状态登录和有状态登录,">










<meta name="description" content="基于JWT的Token认证机制以及实现😊">
<meta name="keywords" content="Json Web Token,token,JJWT,SpringSecurity,认证机制,无状态登录和有状态登录">
<meta property="og:type" content="article">
<meta property="og:title" content="基于JWT的Token认证机制以及实现">
<meta property="og:url" content="https://www.babywang.huangsm.xyz/2019/01/26/基于JWT的Token认证机制以及实现/index.html">
<meta property="og:site_name" content="babybabywang">
<meta property="og:description" content="基于JWT的Token认证机制以及实现😊">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/01/26/基于JWT的Token认证机制以及实现/Cookie认证机制.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/01/26/基于JWT的Token认证机制以及实现/OAuth认证机制.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/01/26/基于JWT的Token认证机制以及实现/JwtToken.png">
<meta property="og:updated_time" content="2019-01-26T14:39:40.173Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="基于JWT的Token认证机制以及实现">
<meta name="twitter:description" content="基于JWT的Token认证机制以及实现😊">
<meta name="twitter:image" content="https://www.babywang.huangsm.xyz/2019/01/26/基于JWT的Token认证机制以及实现/Cookie认证机制.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.babywang.huangsm.xyz/2019/01/26/基于JWT的Token认证机制以及实现/">





  <title>基于JWT的Token认证机制以及实现 | babybabywang</title>
  








</head>
<!-- С���� <script type="text/javascript" src="/js/src/love.js"></script> -->

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
		<a href="https://github.com/babybabywang" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style></a>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">babybabywang</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.babywang.huangsm.xyz/2019/01/26/基于JWT的Token认证机制以及实现/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="huangsm">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogHead.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="babybabywang">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">基于JWT的Token认证机制以及实现</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-26T17:56:03+08:00">
                2019-01-26
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JWT/" itemprop="url" rel="index">
                    <span itemprop="name">JWT</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.1k
                </span>
              

              

              
            </div>
          

          
              <div class="post-description">
                  基于JWT的Token认证机制以及实现😊
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="前提要求"><a href="#前提要求" class="headerlink" title="前提要求"></a>前提要求</h1><p><strong>考虑到使用SpringSecurity的BCryptPasswordEncoder盐加密算法所以在服务中引入SpringSecurity</strong></p>
<ol>
<li>引入依赖</li>
</ol>
<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre><ol start="2">
<li>我们在添加了spring security依赖后，所有的地址都被spring security所控制了，我们目前只是需要用到BCrypt密码加密的部分，所以我们要添加一个配置类，配置为所有地址都可以匿名访问</li>
</ol>
<pre><code>/**
 * 安全配置类
 * @author huangsm
 */
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * authorizeRequests所有security全注解配置实现的开端，表示开始说明需要的权限。
     * 需要的权限分两部分，第一部分是拦截的路径，第二部分访问该路径需要的权限。
     * antMatchers表示拦截什么路径，permitAll任何权限都可以访问，直接放行所有。
     * anyRequest()任何的请求，authenticated认证后才能访问
     * and().csrf().disable()；固定写法，标识csrf失效。
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers(&quot;/**&quot;).permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }

    /**
     * 配置BCrypt强哈希方法 每次加密的结果都不一样
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
</code></pre><h1 id="基于JWT的Token认证机制"><a href="#基于JWT的Token认证机制" class="headerlink" title="基于JWT的Token认证机制"></a>基于JWT的Token认证机制</h1><h3 id="关于有状态登录和无状态的登录"><a href="#关于有状态登录和无状态的登录" class="headerlink" title="关于有状态登录和无状态的登录"></a>关于有状态登录和无状态的登录</h3><ul>
<li>有状态登录: 服务器端需要存储用户信息</li>
<li>无状态登录: 服务器端不需要存储用户信息</li>
</ul>
<h3 id="常见的认证机制"><a href="#常见的认证机制" class="headerlink" title="常见的认证机制"></a>常见的认证机制</h3><ol>
<li>HTTP Basic Auth（无状态登录）</li>
</ol>
<pre><code>HTTP Basic Auth简单点说明就是每次请求API时都提供用户的username和password，简言之，Basic Auth是配合RESTful 
API 使用的最简单的认证方式，只需提供用户名密码即可，但由于有把用户名密码暴露给第三方客户端的风险，在生产
环境下被使用的越来越少。因此，在开发对外开放的RESTful API时，尽量避免采用HTTP BasicAuth
</code></pre><ol start="2">
<li><p>Cookie Auth</p>
<pre><code>Cookie认证机制就是为一次请求认证在服务端创建一个Session对象，同时在客户端的浏览器端创建了一个
Cookie对象；通过客户端带上来Cookie对象来与服务器端的session对象匹配来实现状态管理的。默认的，当我
们关闭浏览器的时候，cookie会被删除。但可以通过修改cookie 的expire time使cookie在一定时间内有效。
</code></pre><p> <img src="/2019/01/26/基于JWT的Token认证机制以及实现/Cookie认证机制.png" alt="基于JWT的Token认证机制以及实现"></p>
</li>
<li><p>OAuth</p>
<pre><code>OAuth（开放授权）是一个开放的授权标准，允许用户让第三方应用访问该用户在
某一web服务上存储的私密的资源（如照片，视频，联系人列表），而无需将用户名和
密码提供给第三方应用。
OAuth允许用户提供一个令牌，而不是用户名和密码来访问他们存放在特定服务提供者的数据。每一个令牌授权一
个特定的第三方系统（例如，视频编辑网站)在特定的时段（例如，接下来的2小时内）内访问特定的资源（例如
仅仅是某一相册中的视频）。这样，OAuth让用户可以授权第三方网站访问他们存储在另外服务提供者的某些特定
信息，而非所有
</code></pre><p><strong>下面是OAuth2.0的流程:</strong></p>
</li>
</ol>
<p><img src="/2019/01/26/基于JWT的Token认证机制以及实现/OAuth认证机制.png" alt="OAuth认证机制"></p>
<pre><code>这种基于OAuth的认证机制适用于个人消费者类的互联网产品，如社交类APP等应
用，但是不太适合拥有自有认证权限管理的企业应用。
</code></pre><ol start="4">
<li><p>Token Auth</p>
<pre><code>使用基于 Token 的身份验证方法，在服务端不需要存储用户的登录记录。大概的流程是
这样的：
1.客户端使用用户名跟密码请求登录
2.服务端收到请求，去验证用户名与密码
3.验证成功后，服务端会签发一个 Token，再把这个 Token 发送给客户端
4.客户端收到 Token 以后可以把它存储起来，比如放在 Cookie 里
5.客户端每次向服务端请求资源的时候需要带着服务端签发的 Token
6.服务端收到请求，然后去验证客户端请求里面带着的 Token，如果验证成功，就向
客户端返回请求的数据
</code></pre></li>
</ol>
<p><img src="/2019/01/26/基于JWT的Token认证机制以及实现/JwtToken.png" alt="JwtToken"></p>
<p><strong>Token Auth的优点:</strong></p>
<p>Token机制相对于Cookie机制又有什么好处呢？</p>
<ul>
<li>支持跨域访问: Cookie是不允许垮域访问的，这一点对Token机制是不存在的，前提<br>是传输的用户认证信息通过HTTP头传输.</li>
<li>无状态(也称：服务端可扩展行):Token机制在服务端不需要存储session信息，因为<br>Token 自身包含了所有登录用户的信息，只需要在客户端的cookie或本地介质存储<br>状态信息.</li>
<li>更适用CDN: 可以通过内容分发网络请求你服务端的所有资料（如：javascript，<br>HTML,图片等），而你的服务端只要提供API即可.</li>
<li>去耦: 不需要绑定到一个特定的身份验证方案。Token可以在任何地方生成，只要在<br>你的API被调用的时候，你可以进行Token生成调用即可.<br>更适用于移动应用: 当你的客户端是一个原生平台（iOS, Android，Windows 8等）<br>时，Cookie是不被支持的（你需要通过Cookie容器进行处理），这时采用Token认<br>证机制就会简单得多。</li>
<li>CSRF:因为不再依赖于Cookie，所以你就不需要考虑对CSRF（跨站请求伪造）的防<br>范。</li>
<li>性能: 一次网络往返时间（通过数据库查询session信息）总比做一次HMACSHA256<br>计算 的Token验证和解析要费时得多.</li>
<li>不需要为登录页面做特殊处理: 如果你使用Protractor 做功能测试的时候，不再需要<br>为登录页面做特殊处理.</li>
<li>基于标准化:你的API可以采用标准化的 JSON Web Token (JWT). 这个标准已经存在<br>多个后端库（.NET, Ruby, Java,Python, PHP）和多家公司的支持（如：<br>Firebase,Google, Microsoft）.<h3 id="基于JWT的Token认证机制实现"><a href="#基于JWT的Token认证机制实现" class="headerlink" title="基于JWT的Token认证机制实现"></a>基于JWT的Token认证机制实现</h3></li>
</ul>
<ol>
<li><p>什么是JWT?</p>
<pre><code>JSON Web Token（JWT）是一个非常轻巧的规范。这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息.
</code></pre></li>
<li><p>JWT组成</p>
<pre><code>一个JWT实际上就是一个字符串，它由三部分组成，头部、载荷与签名。
</code></pre></li>
</ol>
<p><strong>头部（Header）</strong></p>
<pre><code>    头部用于描述关于该JWT的最基本的信息，例如其类型以及签名所用的算法等。这也可以被表示成一个JSON对象。


{&quot;typ&quot;:&quot;JWT&quot;,&quot;alg&quot;:&quot;HS256&quot;}


    在头部指明了签名算法是HS256算法。 我们进行BASE64编码http://base64.xpcha.com/，编码后的字符串如下：
    eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1Ni
</code></pre><blockquote>
<p>小知识：Base64是一种基于64个可打印字符来表示二进制数据的表示方法。由于2的6次方等于64，所以每6个比特为一个单元，对应某个可打印字符。三个字节有24个比特，对应于4个Base64单元，即3个字节需要用4个可打印字符来表示。JDK 中提供了非常方便的 BASE64Encoder 和 BASE64Decoder，用它们可以非常方便的完成基于 BASE64 的编码和解码</p>
</blockquote>
<p><strong>载荷（playload）</strong></p>
<pre><code>载荷就是存放有效信息的地方。这个名字像是特指飞机上承载的货品，这些有效信息包含三个部分

（1）标准中注册的声明（建议但不强制使用）
    iss: jwt签发者
    sub: jwt所面向的用户
    aud: 接收jwt的一方
    exp: jwt的过期时间，这个过期时间必须要大于签发时间
    nbf: 定义在什么时间之前，该jwt都是不可用的.
    iat: jwt的签发时间
    jti: jwt的唯一身份标识，主要用来作为一次性token,从而回避重放攻击。

（2）公共的声明
    公共的声明可以添加任何的信息，一般添加用户的相关信息或其他业务需要的必要信息.
    但不建议添加敏感信息，因为该部分在客户端可解密.

（3）私有的声明
    私有声明是提供者和消费者所共同定义的声明，一般不建议存放敏感信息，因为base64
    是对称解密的，意味着该部分信息可以归类为明文信息。
    这个指的就是自定义的claim。比如前面那个结构举例中的admin和name都属于自定的
    claim。这些claim跟JWT标准规定的claim区别在于：JWT规定的claim，JWT的接收方在
    拿到JWT之后，都知道怎么对这些标准的claim进行验证(还不知道是否能够验证)；而
    private claims不会验证，除非明确告诉接收方要对这些claim进行验证以及规则才行.
</code></pre><p><em>定义一个payload:</em></p>
<pre><code>{&quot;sub&quot;:&quot;1234567890&quot;,&quot;name&quot;:&quot;John Doe&quot;,&quot;admin&quot;:true}
</code></pre><p><em>然后将其进行base64编码，得到Jwt的第二部分。</em></p>
<pre><code>eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
</code></pre><p><strong>签证（signature）</strong></p>
<p><em>jwt的第三部分是一个签证信息，这个签证信息由三部分组成</em></p>
<pre><code>    header (base64后的)
    payload (base64后的)
    secr

这个部分需要base64加密后的header和base64加密后的payload使用.连接组成的字符串，然后通过header中声明的
加密方式进行加盐secret组合加密，然后就构成了jwt的第三部分。

TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

将这三部分用.连接成一个完整的字符串,构成了最终的jwt:
</code></pre><blockquote>
<p>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIi<br>wiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ</p>
</blockquote>
<pre><code>注意：secret是保存在服务器端的，jwt的签发生成也是在服务器端的，secret就是用来进行jwt的签发和jwt的验证，
所以，它就是你服务端的私钥，在任何场景都不应该流露出去。一旦客户端得知这个secret, 那就意味着客户端是可以自我签发jwt了。
</code></pre><h3 id="Java的JJWT实现JWT"><a href="#Java的JJWT实现JWT" class="headerlink" title="Java的JJWT实现JWT"></a>Java的JJWT实现JWT</h3><ol>
<li><p>什么是JJWT？</p>
<pre><code>JJWT是一个提供端到端的JWT创建和验证的Java库。永远免费和开源(Apache
License，版本2.0)，JJWT很容易使用和理解。它被设计成一个以建筑为中心的流畅界
面，隐藏了它的大部分复杂性。
</code></pre></li>
<li><p>token的创建</p>
<pre><code>一、引入依赖

&lt;dependency&gt;
    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;
    &lt;artifactId&gt;jjwt&lt;/artifactId&gt;
    &lt;version&gt;0.6.0&lt;/version&gt;
&lt;/dependency&gt;

二、创建类JwtTest，用于生成token

/**
 * 测试生产Json Web Token
 */
public class CreateJwt {
    public static void main(String[] args) {
        /**
         * signWith实现签名算法和盐(huangsm是盐)
         * setIssuedAt用于设置签发时间
         * signWith用于设置签名秘钥
         * setExpiration设置过期时间
         */
        //为了方便测试，我们将过期时间设置为1分钟
        long now = System.currentTimeMillis();// 当前时间
        long exp = now + 1000 * 60;//过期时间为1分钟
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(&quot;666&quot;)
                .setSubject(&quot;你号&quot;)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, &quot;huangsm&quot;)
                .setExpiration(new Date(exp));
        System.out.println(jwtBuilder.compact());
    }
}
</code></pre></li>
</ol>
<ol start="3">
<li>token的解析</li>
</ol>
<pre><code>我们刚才已经创建了token ，在web应用中这个操作是由服务端进行然后发给客户
端，客户端在下次向服务端发送请求时需要携带这个token（这就好像是拿着一张门票一
样），那服务端接到这个token 应该解析出token中的信息（例如用户id）,根据这些信息
查询数据库返回相应的结果。

解析类:
/**
 * JWT解析
 *
 * @author huangsm
 */
public class ParseJwt {
    public static void main(String[] args) {
        String token = &quot;eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjYiLCJzdWIiOiLkvaDlj7ciLCJpYXQiOjE1NDg1MDI5NzZ9.-MhnLDDDmdsT6c8CX1qXA-kM2HneEgdxIrNH5_54Jn8&quot;;
        Claims claims = Jwts.parser().setSigningKey(&quot;huangsm&quot;)
                .parseClaimsJws(token).getBody();
        System.out.println(&quot;用户ID:&quot;+claims.getId());
        System.out.println(&quot;用户名称:&quot;+claims.getSubject());
        System.out.println(&quot;登录时间:&quot;+claims.getIssuedAt());

    }
}
</code></pre><p><em>试着将token或签名秘钥篡改一下，会发现运行时就会报错，所以解析token也就是验证token</em></p>
<ol start="4">
<li>自定义claims</li>
</ol>
<blockquote>
<p>我们刚才的例子只是存储了id和subject两个信息，如果你想存储更多的信息（例如角<br>色）可以定义自定义claims </p>
</blockquote>
<pre><code>/**
 * 测试生产Json Web Token
 */
public class CreateJwt {
    public static void main(String[] args) {
        /**
         * signWith实现签名算法和盐(huangsm是盐)
         * setIssuedAt用于设置签发时间
         * signWith用于设置签名秘钥
         * setExpiration设置过期时间
         * claim自定义claim
         */
        //为了方便测试，我们将过期时间设置为1分钟
        long now = System.currentTimeMillis();// 当前时间
        long exp = now + 1000 * 60;//过期时间为1分钟
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(&quot;666&quot;)
                .setSubject(&quot;你号&quot;)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, &quot;huangsm&quot;)
                .setExpiration(new Date(exp))
                .claim(&quot;role&quot;,&quot;admin&quot;)
                .claim(&quot;image&quot;,&quot;login.png&quot;);
        System.out.println(jwtBuilder.compact());
    }
}
</code></pre>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Adhere to the original technology sharing, your support will encourage me to continue to create!</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/wx.jpg" alt="huangsm 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/zfb.jpg" alt="huangsm 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Json-Web-Token/" rel="tag"><i class="fa fa-tag"></i> Json Web Token</a>
          
            <a href="/tags/token/" rel="tag"><i class="fa fa-tag"></i> token</a>
          
            <a href="/tags/JJWT/" rel="tag"><i class="fa fa-tag"></i> JJWT</a>
          
            <a href="/tags/SpringSecurity/" rel="tag"><i class="fa fa-tag"></i> SpringSecurity</a>
          
            <a href="/tags/认证机制/" rel="tag"><i class="fa fa-tag"></i> 认证机制</a>
          
            <a href="/tags/无状态登录和有状态登录/" rel="tag"><i class="fa fa-tag"></i> 无状态登录和有状态登录</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/26/RabbitMQ在用户微服务开发中的实战/" rel="next" title="RabbitMQ在用户微服务开发中的实战">
                <i class="fa fa-chevron-left"></i> RabbitMQ在用户微服务开发中的实战
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/26/基于JWT的微服务鉴权开发实现/" rel="prev" title="基于JWT的微服务鉴权开发实现">
                基于JWT的微服务鉴权开发实现 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blogHead.jpg" alt="huangsm">
            
              <p class="site-author-name" itemprop="name">huangsm</p>
              <p class="site-description motion-element" itemprop="description">Make a silk purse out of a self</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">36</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">104</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/wangyuanbaby" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-globe"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/babybabywang" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/weixin_36964056" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/wangyuanbaby" title="码云🐴" target="_blank">码云🐴</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.huangsm.xyz:7900/" title="Eureka服务器" target="_blank">Eureka服务器</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前提要求"><span class="nav-number">1.</span> <span class="nav-text">前提要求</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#基于JWT的Token认证机制"><span class="nav-number">2.</span> <span class="nav-text">基于JWT的Token认证机制</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#关于有状态登录和无状态的登录"><span class="nav-number">2.0.1.</span> <span class="nav-text">关于有状态登录和无状态的登录</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常见的认证机制"><span class="nav-number">2.0.2.</span> <span class="nav-text">常见的认证机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基于JWT的Token认证机制实现"><span class="nav-number">2.0.3.</span> <span class="nav-text">基于JWT的Token认证机制实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java的JJWT实现JWT"><span class="nav-number">2.0.4.</span> <span class="nav-text">Java的JJWT实现JWT</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HUANGSM</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

</body>
</html>
